package com.open.capacity.workflow.service.impl;

import com.open.capacity.commons.Result;
import com.open.capacity.finance.util.uuid.UUIDUtils;
import com.open.capacity.workflow.dao.WFDelegateRecordDao;
import com.open.capacity.workflow.model.WFDelegateRecord;
import com.open.capacity.workflow.service.WFDelegateRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Slf4j
@Service
public class WFDelegateRecordServiceImpl implements WFDelegateRecordService {

    @Autowired
    private WFDelegateRecordDao delegateRecordDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(WFDelegateRecord delegateRecord) {

        delegateRecordDao.save(delegateRecord);
        log.info("保存委托记录：{}", delegateRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(WFDelegateRecord delegateRecord) {

        delegateRecordDao.updateByOps(delegateRecord);
        log.info("修改委托记录：{}", delegateRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(String id) {
        WFDelegateRecord delegateRecord = delegateRecordDao.findById(id);

        delegateRecordDao.delete(id);

        log.info("删除委托记录：{}", delegateRecord);
    }


    @Override
    public WFDelegateRecord findById(String id) {
        return delegateRecordDao.findById(id);
    }

    @Override
    public List<WFDelegateRecord> findDelegateRecords(Map<String, Object> params) {
//        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
//        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
//            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);
        List<WFDelegateRecord> list = delegateRecordDao.findList(params);
        return list;
    }


    @Override
    public Result saveOrUpdate(WFDelegateRecord delegateRecord, String keyValue) {
        int i = 0;

        if (StringUtils.isNotEmpty(keyValue)) {
            WFDelegateRecord model = delegateRecordDao.findById(keyValue);
            if (model != null) {
                delegateRecord.setId(keyValue);
                i = delegateRecordDao.updateByOps(delegateRecord);
            }
        } else {
            delegateRecord.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            delegateRecord.setCreateTime(new Date());
            i = delegateRecordDao.save(delegateRecord);
        }

        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }
}
